import aiohttp
import aiofiles
import hashlib

import mp3
import config

from .os import listdir, rename

import re
def no_translate(s):
	try:
		return re.sub(r" ?\(.+\)", "", s)
	except:
		print("Exception", s)

async def wget(url: str, filename: str=None):
	""" async requests.get(url) """

	session = aiohttp.ClientSession()
	resp = await session.get(url)
	content = await resp.read()
	await session.close()
	if filename is not None:
		async with aiofiles.open(filename, "wb") as f:
			await f.write(content)
	return content

def hash(s: str):
	return hashlib.md5(s.encode("utf-8")).hexdigest()


def _correlate(songs, folder):
	res = {}
	for filename in listdir(folder):
		if not filename.endswith(".mp3"):
			continue

		def pre(s: str):
			return s.strip().lower().replace("ё", "е")

		for song in songs:
			title = no_translate(song["title"])
			if pre(title) in pre(filename) or pre(filename[:-4]) in pre(title):
				song["founded"] = True
				break
			title = None

		if title is None:
			print(title)
			continue

		res[filename] = song

	return res


def format(s: str, obj):
	if "{number}" in s:
		number = f'{obj.get("number")}'
		length = f'{obj["album_length"]}'

		number = f"{'0'*(len(length) - len(number))}{number}"

		s = s.replace("{number}", number)

	return s.format(
		artist=no_translate(obj["artist"]),
		title=no_translate(obj["title"])
	)

async def set_meta_to_albumfolder(album, path):
	for name, song in _correlate(album["songs"], path).items():
		song["album_length"] = len(album["songs"])


		filename = path + "/" + format(
			config.track_filename_template, song
		).replace("/", "-")

		mp3.set_meta(f"{path}/{name}", song, album)
		await rename(f"{path}/{name}", filename)